<?php
class Script extends CI_Controller
{
    public $config;
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $CI = &get_instance();
        $CI->load->config('public');
        $this->config = $CI->config->item('public');
    }
    //更新父级
    public function editParent()
    {
        $user_id = empty($_GET['user_id']) ? 0 : $_GET['user_id'];
        $where = 'id= ' . $user_id . ' and update_parent = 1';
        ignore_user_abort(true);
        ini_set('max_execution_time', '0');
        ini_set('memory_limit', '-1');
        $users = $this->user_model->getUserIds($where);
        $num = 0;
        foreach ($users as $k => $v) {
            $this->user_model->editUser(array('id' => $v['id']), array('parent_id' => $this->config['parent_id'], 'update_parent' => 2));
            //将独立出去的高管业绩记录在当前独立出去的用户的父级数据中duli_xiaji 字段中 格式[{"id":1,"yeji":2}]
            $parentUser = $this->user_model->checkUser(array('id' => $v['parent_id']));
            if (!empty($parentUser['dulixiaji'])) {
                $parentUser['dulixiaji'] = json_decode($parentUser['dulixiaji'], 1);
            } else {
                $parentUser['dulixiaji'] = array();
            }
            $parentUser['dulixiaji'][] = array('user_id' => $v['id'], 'yeji' => $parentUser['score'] + $parentUser['price']);
            $this->user_model->editUser(array('id' => $v['parent_id']), array('dulixiaji' => json_encode($parentUser['dulixiaji'], 320)));

            $parent_path = $v['parent_path'];
            //将上级中最近的两级更新为需要更新下级和下下级数量
            $parentIds = explode(',', $parent_path);
            $parentIds = array_diff($parentIds, [$v['id']]);
            error_log('父级id1：' . var_export($parentIds, 1) . "\n", 3, 'user.log');
            $parentIds = array_unique(array_filter($parentIds));
            error_log('父级id2：' . var_export($parentIds, 1) . "\n", 3, 'user.log');
            if (!empty($parentIds)) {
                $parentIds = array_values($parentIds);
                $this->user_model->editUserByIds(array($parentIds[0], $parentIds[1]), array('update_parent' => 3));
            }
            //获取下级，将下级更新为需要更新下级的父级路径
            $childenUsers = $this->user_model->getChainList($v['id'], 'id');
            if (!empty($childenUsers)) {
                $childenUserIds = array_column($childenUsers, 'id');
                $this->user_model->editUserByIds($childenUserIds, array('update_parent' => 2));
            }
            error_log('用户：' . $v['id'] . 'parent_path:' . $parent_path . "\n", 3, 'user.log');
            $num++;
        }
        $result = array('code' => 200, 'msg' => '执行成功', 'count' => $num);
        echo json_encode($result);
    }
    //更新父级路径
    public function retryPath()
    {
        $where = ' update_parent = 2';
        ignore_user_abort(true);
        ini_set('max_execution_time', '0');
        ini_set('memory_limit', '-1');
        $users = $this->user_model->getUserIds($where);
        $num = 0;
        foreach ($users as $k => $v) {
            // if ($v['parent_path']) continue;
            $parent_path = $this->user_model->getParent_id(array('id' => $v['id']));
            $this->user_model->editUser(array('id' => $v['id']), array('parent_path' => $parent_path, 'update_parent' => 0));
            /*
            //将上级中最近的两级更新为需要更新下级和下下级数量
            $parentIds = explode(',', $parent_path);
            $parentIds = array_diff($parentIds, [$v['id']]);
            $parentIds = array_unique(array_filter($parentIds));
            if (!empty($parentIds)) {
            $parentIds = array_values($parentIds);
            $this->user_model->editUserByIds(array($parentIds[0], $parentIds[1]), array('update_parent' => 3));
            }
            //获取下级，更新下级的父级路径
            $childenUsers = $this->user_model->getChainList($v['id'], 'id');
            if (!empty($childenUsers)) {
            $childenUserIds = array_column($childenUsers, 'id');
            $this->user_model->editUserByIds(array($parentIds[0], $parentIds[1]), array('update_parent' => 2));
            }*/
            error_log('用户：' . $v['id'] . 'parent_path:' . $parent_path . "\n", 3, 'user.log');
            $num++;
        }
        $result = array('code' => 200, 'msg' => '执行成功', 'count' => $num);
        echo json_encode($result);
    }
    public function nextCount()
    {

        $type = isset($_GET['type']) ? $_GET['type'] : 'nextCount';
        if ($type == 'nextCount') {
            $where = ' update_parent = 3';
        } else {
            $where = ' update_parent = 4';
        }

        ignore_user_abort(true);
        ini_set('max_execution_time', '0');
        ini_set('memory_limit', '-1');

        $users = $this->user_model->getUserIds($where);
        $users[] = array('id' => 1);
        $num = 0;
        if ($type == 'nextCount') {
            foreach ($users as $k => $v) {
                // if ($v['parent_path']) continue;
                $next_count = $this->user_model->getNextCount($v['id']);
                $this->user_model->editUser(array('id' => $v['id']), array('next_count' => $next_count, 'update_parent' => 4));
                // echo $next_count . "<br/>";
                error_log($v['id'] . 'next_count:' . $next_count . "\n", 3, 'user.log');
                $num++;
            }
        } else {
            foreach ($users as $k => $v) {
                // if ($v['parent_path']) continue;
                $next_next_count = $this->user_model->getNextNextCount($v['id']);
                $this->user_model->editUser(array('id' => $v['id']), array('next_next_count' => $next_next_count, 'update_parent' => 0));
                // echo $next_next_count . "<br/>";
                error_log($v['id'] . 'next_next_count:' . $next_next_count . "\n", 3, 'user.log');
                $num++;
            }
        }
        $result = array('code' => 200, 'msg' => '执行成功', 'count' => $num);
        echo json_encode($result);
    }
    /**
     * php异步请求
     * @param $host string 主机地址
     * @param $path string 路径
     * @param $param array 请求参数
     * @return string
     */
    public static function asyncRequest($url, $param = array(), $port = 80, $header = array())
    {
        $urlinfo = parse_url($url);
        //$host = $urlinfo['host'] = 'localhost';
        // $urlinfo['host'] = str_replace('10.2.7.108','127.0.0.1',$urlinfo['host']);
        $host = $urlinfo['host'];
        $path = $urlinfo['path'];
        $query = isset($param) ? http_build_query($param) : '';

        $errno = 0;
        $errstr = '';
        $timeout = 18000; //连接超时时间（S）

        $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
        //$fp = stream_socket_client("tcp://".$host.":".$port, $errno, $errstr, $timeout);

        if (!$fp) {

            return '连接失败';
        }
        if ($errno || !$fp) {

            return $errstr;
        }

        stream_set_blocking($fp, 0); //非阻塞
        stream_set_timeout($fp, 300); //响应超时时间（S）
        $out = "POST " . $path . " HTTP/1.1\r\n";
        $out .= "host:" . $host . "\r\n";
        $out .= "content-length:" . ($query) . "\r\n";
        $out .= "content-type:application/x-www-form-urlencoded\r\n";
        $out .= "connection:close\r\n\r\n";
        $out .= $query;

        $result = @fputs($fp, $out);
        usleep(3000);

        @fclose($fp);
        return $result;
    }
}
